﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Ionic;
using NetTaste;
using Newtonsoft.Json;
using SM23;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using TlToolBase;
using TlToolBase.Mode;
using TlToolCordCreate.Mode;
using TlToolCordCreate.Web;

namespace TlToolCordCreate.ViewMode
{
    /// <summary>
    /// 界面数据
    /// </summary>
    public class UiData : ObservableObject
    {

        public MyWebRequest webRequest { get; set; }
        private Config _config;
        /// <summary>
        /// 配置
        /// </summary>
        public Config config { get => _config; set => SetProperty(ref _config, value); }
        /// <summary>
        /// 表属性
        /// </summary>

        private List<TableProperties> _tableProperties;
        /// <summary>
        /// 表属性
        /// </summary>
        public List<TableProperties> TablePropertiesList { get => _tableProperties; set => SetProperty(ref _tableProperties, value); }

        public bool _hasToken;
        /// <summary>
        /// 是否有token
        /// </summary>
        public bool HasToken { get => _hasToken; set => SetProperty(ref _hasToken, value); }

        public ICommand FileSelectCommand { get; set; }
        public ICommand CreateCodeCommand { get; set; }
        public ICommand SaveCodeCommand { get; set; }
        public ICommand GetTokenCommand { get; set; }
        public ICommand WebSaveCodeCommand { get; set; }
        public ICommand WebSaveBusinessCodeCommand { get; set; }

        public UiData()
        {
            config = FileDataClass.Get<Config>();
            webRequest = new();
            webRequest.ServerIP = config.ServerIP;
            webRequest.ServerPort = config.ServerPort;
            FileSelectCommand = new RelayCommand(FileSelect);
            SaveCodeCommand = new RelayCommand(SaveCode);
            GetTokenCommand = new RelayCommand(GetToken);
            WebSaveCodeCommand = new RelayCommand(WebSaveCode);
            WebSaveBusinessCodeCommand = new RelayCommand(WebSaveBusinessCode);
            TablePropertiesList = new List<TableProperties>();
            TablePropertiesList.Add(new TableProperties() { TableDescribe = "1", TableName = "1" });
        }

        private void WebSaveBusinessCode()
        {
            Task.Run(() =>
            {
                for (global::System.Int32 i = 0; i < TablePropertiesList.Count; i++)
                {
                    if (TablePropertiesList[i].DontCreate!="1")
                    {
                        Console.WriteLine(string.Format("开始创建业务{0}", i));
                        TablePropertiesList[i].WebCreateBusinessCodeCommand.Execute(this);
                        while (true)
                        {
                            Console.WriteLine(string.Format("创建业务{0}ing", i));
                            if (TablePropertiesList[i].CreateCodeTaskFlag == 4)
                            {
                                break;
                            }
                            Thread.Sleep(1000);
                        }
                        Console.WriteLine(string.Format("创建业务{0}结束", i));
                    }
                }
            });
        }

        /// <summary>
        /// 使用web接口生成实体
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void WebSaveCode()
        {
            foreach (var table in TablePropertiesList)
            {
                if (table.DontCreate != "1")
                {
                    table.WebCreateEntityCodeCommand.Execute(this);
                    Thread.Sleep(1000);
                }
            }
        }

        /// <summary>
        /// 获取token
        /// </summary>
        private void GetToken()
        {
            webRequest.ServerIP = config.ServerIP;
            webRequest.ServerPort = config.ServerPort;
            webRequest.GetToken(new Action<bool>((callback) =>
            {
                HasToken = callback;
            }));
        }

        /// <summary>
        /// 代码保存
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void SaveCode()
        {
            foreach (var table in TablePropertiesList)
            {
                if (table.DontCreate!="1")
                {
                    table.CodeSaveCommand.Execute(config.SavePath);
                    table.CreateDBTableCommand.Execute(null);
                }
            }
        }


        /// <summary>
        /// 文件加载 本来想选择文件 后来想放弃了直接加载
        /// 
        /// </summary>
        private void FileSelect()
        {
            FileDataClass.Save<Config>(config);
            var tabledatas = FileHelp.LoadExcel(ProgramConstant.ExcelFilePath);
            if (!tabledatas.Success)
            {
                return;
            }
            if (tabledatas.Result.Count==0)
            {
                MessageBox.Show(tabledatas.Message) ;
                return;
            }
            int filemode = 1;
            List<TableProperties> TablePropertiesLists = new List<TableProperties>();
            foreach (var tabledata in tabledatas.Result)
            {
                if (tabledata.Value.Rows.Count > 2)
                {
                    if (filemode == 0)
                    {
                        TableProperties tableProperties = new TableProperties()
                        {
                            Fields = new List<FieldProperties>(),
                            IsDelectTable = true,
                        };
                        tableProperties.TableName = tabledata.Key;
                        tableProperties.ClassName = StringHelp.ToCamelCase(tabledata.Key);
                        tableProperties.TableDescribe = tabledata.Value.Columns[3].ToString();
                        tableProperties.DontCreate= tabledata.Value.Columns[3].ToString();
                        for (global::System.Int32 i = 1; i < tabledata.Value.Rows.Count; i++)
                        {
                            FieldProperties field = new FieldProperties();
                            field.PropertiesType = tabledata.Value.Rows[i][2].ToString();
                            field.PropertiesName = tabledata.Value.Rows[i][1].ToString();
                            field.Description = tabledata.Value.Rows[i][0].ToString();
                            if (tabledata.Value.Rows[i][4].ToString().ToLower() == Boolean.TrueString.ToLower())
                            {
                                field.CanNull = true;
                            }
                            else
                            {
                                field.CanNull = false;
                            }
                            if (tabledata.Value.Rows[i][3].ToString().ToLower() == Boolean.TrueString.ToLower())
                            {
                                field.Primarykey = true;
                                if (field.PropertiesName == "ID")
                                {
                                    field.IsIdentity = true;
                                }
                            }
                            tableProperties.Fields.Add(field);
                        }
                        TablePropertiesLists.Add(tableProperties);
                    }
                    else
                    {
                        //
                        int hascout = 0;
                        string[] titles = new string[] { "表名", "描述", "名称", "字段", "类型", "主键", "可空", "创建忽略" };
                        for (global::System.Int32 i = 0; i < titles.Length; i++)
                        {
                            if (tabledata.Value.Columns[i].ColumnName == titles[i])
                            {
                                hascout++;
                            }
                        }
                        if (hascout == titles.Length)
                        {
                            string table = "";
                            TableProperties tp = null;
                            for (global::System.Int32 i = 0; i < tabledata.Value.Rows.Count; i++)
                            {
                                string tab = tabledata.Value.Rows[i][0].ToString();
                                if (tab != "")
                                {
                                    if (table != tab)
                                    {
                                        table = tab;
                                        if (tp != null)
                                        {
                                            TablePropertiesLists.Add(tp);
                                        }
                                        tp = new TableProperties()
                                        {
                                            Fields = new List<FieldProperties>(),
                                            IsDelectTable = true,
                                        };
                                        tp.TableName = tab;
                                        tp.ClassName = StringHelp.ToCamelCase(tab);
                                        tp.TableDescribe = tabledata.Value.Rows[i][1].ToString();
                                        tp.DontCreate = tabledata.Value.Rows[i][7].ToString();
                                    }
                                }
                                if (table != "")
                                {
                                    string Description = tabledata.Value.Rows[i][2].ToString();
                                    if (Description!="")
                                    {
                                        FieldProperties field = new FieldProperties();
                                        field.PropertiesType = tabledata.Value.Rows[i][4].ToString();
                                        field.PropertiesName = tabledata.Value.Rows[i][3].ToString();
                                        field.Description = Description;
                                        if (tabledata.Value.Rows[i][6].ToString().ToLower() == Boolean.TrueString.ToLower())
                                        {
                                            field.CanNull = true;
                                        }
                                        else
                                        {
                                            field.CanNull = false;
                                        }
                                        if (tabledata.Value.Rows[i][5].ToString().ToLower() == Boolean.TrueString.ToLower())
                                        {
                                            field.Primarykey = true;
                                            if (field.PropertiesName == "ID")
                                            {
                                                field.IsIdentity = true;
                                            }
                                        }
                                        tp.Fields.Add(field);
                                    }
                                }
                            }
                            if (tp != null)
                            {
                                TablePropertiesLists.Add(tp);
                            }
                        }
                    }


                }
            }
            TablePropertiesList = TablePropertiesLists;
        }
    }
}
